<template>
  <div id="productCategroys">
    <!-- 右侧卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="6">
        <el-col :span="5">
          <el-cascader
            placeholder="请选择分类查询"
            @change="selectChange"
            v-model="categoryKeys"
            :props="searchSelectProps"
            :options="catetorys"
            collapse-tags
            clearable
          ></el-cascader>
        </el-col>
        <el-col :span="6">
          <el-input
            clearable=""
            v-model="queryMap.name"
            placeholder="请输入物资名称查询"
            @clear="search"
            class="input-with-select"
          ></el-input>
        </el-col>
        <el-col :span="5">
          <template>
            <el-select v-model="queryMap.status" @click.native="search" placeholder="请选择状态" value="">
              <el-option v-for="item in status"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value"
                         @click.native="search"
              ></el-option>
            </el-select>
          </template>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" icon="el-icon-search" @click="search">查找</el-button>
          <el-button icon="el-icon-refresh-right" type="warning" @click="resetSearchForm">重置</el-button>
          <el-button type="success" icon="el-icon-circle-plus-outline" @click="openAdd">添加</el-button>
          <el-button icon="el-icon-refresh" @click="getProductList">刷新</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <template>
        <el-table
          v-loading="loading"
          border
          stripe
          :data="productData"
          style="width: 100%;margin-top:20px;"
          height="400"
        >
          <el-table-column prop="id" label="ID" width="50px"></el-table-column>

          <el-table-column prop="imageUrl" label="图片" align="center" width="150px">
            <template slot-scope="scope">
              <el-image :src="scope.row.imageUrl" style="width: 40px;height: 40px">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="物资名称"></el-table-column>
          <el-table-column prop="pnum" :show-overflow-tooltip='true' label="物资编号"></el-table-column>
          <el-table-column label="物资规格" width="100">
            <template slot-scope="scope">
              <el-tag type="success" size="mini" closable v-text="scope.row.model"></el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag size="mini" type="danger" effect="plain" v-if="scope.row.status===1">回收</el-tag>
              <el-tag size="mini" effect="plain" v-if="scope.row.status===0">正常</el-tag>
              <el-tag size="mini" effect="plain" type="warning" v-if="scope.row.status===2">审核中</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <!--给操作员提供的编辑和回收-->
              <span v-if="scope.row.status===0">
                <el-button type="text" size="mini" icon="el-icon-edit"
                           @click="edit(scope.row)">编辑</el-button>
                <el-popconfirm
                  @confirm="remove(scope.row.id)"
                  style="margin-left:10px;"
                  confirmButtonText='好的'
                  cancelButtonText='不用了'
                  icon="el-icon-info"
                  iconColor="red"
                  title="这是一段内容确定移入回收站吗？"
                >
                  <el-button type="text" slot="reference" size="mini" icon="el-icon-s-operation">回收站</el-button>
                </el-popconfirm>
              </span>

              <!--给管理员提供的恢复和删除-->
              <span v-if="scope.row.status===1">
                 <el-popconfirm
                   @confirm="back(scope.row.id)"
                   style="margin-left:10px;"
                   confirmButtonText='好的'
                   cancelButtonText='不用了'
                   icon="el-icon-info"
                   iconColor="green"
                   title="这是一段内容确定恢复吗？"
                 >
                <el-button type="text" size="mini" slot="reference" icon="el-icon-back">恢复</el-button>
                 </el-popconfirm>
              <el-button style="margin-left:10px;" type="text" size="mini" icon="el-icon-delete"
                         @click="del(scope.row)">删除</el-button>
              </span>

              <!--给管理员提供的审核和不通过-->
              <span v-if="scope.row.status===2">
              <el-popconfirm
                @confirm="publish(scope.row.id)"
                style="margin-left:10px;"
                confirmButtonText='是的'
                cancelButtonText='不用了'
                icon="el-icon-info"
                iconColor="blue"
                title="确定审核通过吗？"
              >
              <el-button type="text" slot="reference" size="mini" icon="el-icon-s-operation">通过</el-button>
            </el-popconfirm>
              <el-button style="margin-left:10px;" type="text" size="mini" icon="el-icon-delete"
                         @click="del(scope.row)">删除</el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        style="margin-top:10px;"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 10, 15, 20]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 物资添加或修改弹出框 -->
      <el-dialog :title="title" :modal-append-to-body="false" :visible.sync="open" width="50%" @close="closeAddDialog">
        <span>
          <el-form
            :model="form"
            :rules="addRules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="物资名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="物资图片" prop="name">
              <!-- 图片上传部分 -->
              <div>
                  <img style="height: 80px;width: 80px;cursor:pointer "
                       :src="form.imageUrl+''"
                       title="点击上传图片"
                       @click="imagecropperShow=true"
                       alt=""/>
                <span>上传后自动修改</span>
              </div>
              <el-form :model="form" size="medium" label-width="100px">
                <el-form-item>
                  <image-cropper
                    v-show="imagecropperShow"
                    :width="300" :height="300"
                    :key="imagecropperKey"
                    :url="'/uploadImgFile'"
                    field="file"
                    @close="closeImage"
                    @crop-upload-success="cropSuccess"/>
                </el-form-item>
              </el-form>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="物资规格" prop="model">
                    <el-input v-model="form.model"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="分类" prop="threeCategoryId">
                    <el-cascader
                      :options="catetorys"
                      clearable
                      filterable
                      :props="selectProps"
                      v-model="form.threeCategoryId"
                    ></el-cascader>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="单位" prop="unit">
                    <el-input v-model="form.unit"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" :min="1" :max="10" label="排序"></el-input-number>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-form-item label="备注信息" prop="remark">
              <el-input type="textarea" v-model="form.remark"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeAddDialog">取 消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="btnDisabled" :loading="btnLoading">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 图片预览 -->
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt/>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import ImageCropper from '@/components/ImageCropper/index'
  import { addProduct, back, del, remove, getProductList, publish, updateProduct } from '@/api/biz/product'
  import { getCategory } from '@/api/biz/productCategory'
  import { deleteImgFile } from '@/api/oss'
  import { deleteFileByUrl, saveFile } from '@/api/system/file'

  export default {
    components: {
      ImageCropper,
    },

    data () {
      return {
        imagecropperShow: false, // 是否显示上传组件
        imagecropperKey: 0, // 上传组件id
        btnLoading: false,
        btnDisabled: false,
        loading: true,
        catetorys: [], //类别选择
        selectProps: {
          expandTrigger: 'hover',
          value: 'id',
          label: 'name',
          children: 'children',
          emitPath: false,
          checkStrictly: false
        }, //级联选择器配置项
        searchSelectProps: {
          expandTrigger: 'hover',
          value: 'id',
          label: 'name',
          children: 'children',
          checkStrictly: false,
          multiple: true,
          emitPath: false
        }, //级联搜索选择器配置项
        status: [{
          'label': '正常',
          'value': 0
        }, {
          'label': '回收站',
          'value': 1
        }, {
          'label': '待审核',
          'value': 2
        }],
        open: false,
        size: 6,
        total: 100,
        current: 1,
        title: '',
        productData: [], //表格数据
        queryMap: {
          name: '',
          categoryKeys: '',
          supplier: '',
          status: 0,
        }, //查询对象
        imgFilesList: [],
        categoryKeys: [], //搜索类别
        oldImage: '',
        file: {
          url: null,
          type: '',
          fileName: undefined,
          size: undefined,
        },
        addRuleForm: {}, //添加表单数据
        editRuleForm: {}, //修改表单数据
        form: {},
        uploadDisabled: false,
        limitcount: 1,
        dialogImageUrl: '',
        dialogVisible: false,
        addRules: {
          name: [
            {
              required: true,
              message: '请输入物资名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
          unit: [
            {
              required: true,
              message: '请输入物资单位',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 10,
              message: '长度在 1 到 10 个字符',
              trigger: 'blur'
            }
          ],
          model: [
            {
              required: true,
              message: '请输入物资规格',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
          remark: [
            {
              required: true,
              message: '请输入物资说明备注',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
          sort: [{
            required: true,
            message: '请输入地址信息',
            trigger: 'blur'
          }],
          threeCategoryId: [
            {
              required: true,
              message: '请选择物资分类',
              trigger: 'blur'
            }
          ]
        }, //添加验证
      }
    },
    created () {
      this.getProductList()
      this.getCategory()
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    methods: {
      //重置查询表单
      resetSearchForm () {
        this.queryMap.name = ''
        this.queryMap.categoryKeys = ''
        this.categoryKeys = ''
        this.queryMap.supplier = ''
        this.queryMap.status = 0
        this.reFresh()
      },
      /**
       * 打开添加物资弹框
       */
      openAdd () {
        this.title = '添加物资'
        this.open = true
      },
      /**
       * 打开编辑物资
       */
      edit (row) {
        this.title = '修改物资'
        this.form = JSON.parse(JSON.stringify(row))
        this.oldImage = this.form.imageUrl
        this.open = true
      },

      /** 提交按钮 */
      submitForm: function () {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              this.form.modifiedTime = undefined
              updateProduct(this.form).then(response => {
                if (response.code === 200) {
                  this.$message('修改成功')
                  this.open = false
                  this.$refs.form.resetFields()
                  this.getProductList()
                }
              })
            } else {
              addProduct(this.form).then(response => {
                if (response.code === 200) {
                  this.$message('新增成功')
                  this.open = false
                  this.$refs.form.resetFields()
                  this.getProductList()
                }
              })
            }
          }
        })
      },
      /**
       * 搜索物资
       */
      search () {
        this.current = 1
        this.getProductList()
      },

      reFresh () {
        this.search()
      },

      /**
       * 删除物资
       */
      del (row) {
        this.$confirm('此操作将永久删除该物资, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(row.id).then(res => {
            if (res.code === 200) {
              this.$message('删除成功')
              this.deleteAvatar(row.imageUrl)
              this.deleteFileInMysql(row.imageUrl)
              this.getProductList()
            }
          })
        })
      },
      /**
       * 移至回收站
       */
      remove (id) {
        remove(id).then(res => {
          if (res.code === 200) {
            this.$message('回收成功')
            this.getProductList()
          }
        })
      },

      /**
       * 物资添加审核
       */
      publish (id) {
        publish(id).then(res => {
          if (res.code === 200) {
            this.$message('审核通过')
            this.getProductList()
          }
        })
      },

      /**
       * 从回收站恢复
       */
      back (id) {
        back(id).then(res => {
          if (res.code === 200) {
            this.$message('恢复成功')
            this.getProductList()
          }
        })
      },
      /**
       * 加载物资列表
       */
      getProductList () {
        getProductList(this.current, this.size, this.queryMap).then(res => {
          if (res.code === 200) {
            this.total = res.data.total
            this.productData = res.data.records
          }
        })
      },

      //当每页条数改变
      handleSizeChange (val) {
        this.size = val
        this.getProductList()
      },

      //当前页码改变
      handleCurrentChange (val) {
        this.current = val
        this.getProductList()
      },

      //关闭弹出框
      closeAddDialog () {
       
        if(this.$refs['form']){
              this.$nextTick(()=>{
              this.$refs.form.resetFields();
          })
        }else{
          return;
        }
        this.form = {}
        this.oldImage = ''
        this.open = false
      },

      /**
       * 加载物资类别
       */
      getCategory () {
        getCategory().then(res => {
          if (res.code === 200) {
            this.catetorys = this.deleteNullChildren(res.data.menus)
          }
        })
      },

      //删除children为null的菜单的children属性
      deleteNullChildren (category) {
        for (let i = 0; i < category.length; i++) {
          if (category[i].children.length > 0) {						//判断children的数组长度
            this.deleteNullChildren(category[i].children)
          }
          if (category[i].children.length === 0) {
            category[i].children = undefined
          }
        }
        return category
      },

      /**
       * 分类搜索改变时
       */
      selectChange () {
        let str = ''
        for (let i = 0; i < this.categoryKeys.length; i++) {
          str += this.categoryKeys[i] + ','
        }
        str = str.substring(0, str.length - 1)
        this.queryMap.categoryKeys = str
        console.log(str)
      },
      // 关闭上传组件
      closeImage () {
        this.imagecropperShow = false
        // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
      },
      // 上传成功后的回调函数,自动接收返回数据
      cropSuccess (data) {
        this.imagecropperShow = false
        // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
        //删除最开始的头像和数据库里的文件记录
        if (this.oldImage !== '' && this.oldImage !== null) {
          this.deleteAvatar(this.oldImage)
          this.deleteFileInMysql(this.oldImage)
        }
        //保存上传之前的头像
        console.log(data);
        this.form.imageUrl = this.oldImage = data.url
        console.log(this.file);
        this.file = data.file
        this.addFile()
        if (this.form.id !== undefined) {
          updateProduct(this.form)
        }
      },
      //删除之前在阿里云中的图片
      async deleteAvatar (oldImg) {
        await deleteImgFile(oldImg)
      },

      //删除数据库里的文件记录
      async deleteFileInMysql (oldImg) {
        await deleteFileByUrl(oldImg)
      },
      //添加文件记录
      async addFile () {
        await saveFile(this.file)
      },
    }
  }
</script>

